package com.mail.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.mail.RedisCache.CacheTemplate;
import com.mail.entiy.MailSend;
import com.mail.eunm.MailSatus;
import com.mail.eunm.RedisPriorityQueue;
import com.mail.mapper.MailSend1Mapper;
import com.mail.mapper.MailSend2Mapper;
import com.mail.utils.FastJsonConvertUtil;

@Service("mailSendService")
public class MailSendServiceImpl implements MailSendService {
	private static Logger LOGGER = LoggerFactory.getLogger(MailSendServiceImpl.class);
	@Autowired
	private MailSend1Mapper mailSend1Mapper;
	@Autowired
	private MailSend2Mapper mailSend2Mapper;
	@Autowired
	private CacheTemplate cachedTemplate;
	@Override
	public void send(MailSend mailSend) {
		int hashcode = mailSend.getSendId().hashCode();
		if(hashcode%2==0) {
			mailSend2Mapper.insert(mailSend);
		}else {
			mailSend1Mapper.insert(mailSend);
		}
	}
	@Override
	public void addlist(MailSend mailSend) {
		 Long priority= mailSend.getSendPriority();//级别
		 Long result=0L;
		 Long size=0L; 
		 //只要是信息投递就+1 ,此处的投递成功也只是投递成功，但如果消费端消费失败也必须是重投
		 mailSend.setSendCount(mailSend.getSendCount()+1);
		 if(priority<4L) {
			 //延迟  返回的结果为容器的最新长度
			 result= cachedTemplate.rightPush(RedisPriorityQueue.DEFER_QUEUE.getCode(),FastJsonConvertUtil.convertObjectToJSON(mailSend));
			 //返回列的长度
			 size = cachedTemplate.size(RedisPriorityQueue.DEFER_QUEUE.getCode());
		 }else if(priority>4L && priority<7L) {
			 //普通
			 result= cachedTemplate.rightPush(RedisPriorityQueue.NORMAL_QUEUE.getCode(),FastJsonConvertUtil.convertObjectToJSON(mailSend));
			 size = cachedTemplate.size(RedisPriorityQueue.NORMAL_QUEUE.getCode());
		 }else {
			 //加急
			 result= cachedTemplate.rightPush(RedisPriorityQueue.FAST_QUEUE.getCode(),FastJsonConvertUtil.convertObjectToJSON(mailSend));
			 size = cachedTemplate.size(RedisPriorityQueue.FAST_QUEUE.getCode());
		 }
		 if(result==size) {
			 mailSend.setSendStatus(MailSatus.SEND_IN.getCode());
			 if(mailSend.getSendId().hashCode()%2==0) {
				 mailSend2Mapper.updateByPrimaryKey(mailSend);
			 }else {
				 mailSend1Mapper.updateByPrimaryKey(mailSend);
			 }
			 LOGGER.info("---------------进入队列成功 id :{}", mailSend.getSendId());
		 }else {
			 
			 LOGGER.info("---------------进入队列失败等待轮循 id :{}", mailSend.getSendId());
		 }
	}
}
